<?php

namespace App\Http\Services;
//require_once WEB_ROOT . '/Library/feieyun/HttpClient.php';

//标签说明：
//单标签:
//"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
//"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
//成对标签：
//"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
//<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
//拼凑订单内容时可参考如下格式
//根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式
use App\Library\HttpClient;
use App\Repositories\Manage\PrinterRepository;


/**
 * 飞鹅打印机
 */
class FeieyunService
{
    private $_user = NULL;  //*必填*：飞鹅云后台注册账号
    private $_key = NULL;//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
    private $_sn = NULL;//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API
    private $_secret = NULL;//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API
    private $httpClient = NULL;

    const API_URL = 'api.feieyun.cn';//接口IP或域名
    const API_PORT = 80; //接口IP端口
    const API_PATH = '/Api/Open/';  //接口路径

    public function __construct($options = null)
    {
        $this->_user = env("PRINTER_USER");
        $this->_key = env("PRINTER_KEY");

        $printer = (new PrinterRepository())->getOne($options['id']);
        if (isset($printer)) {
            $this->_secret = $printer['secret'];
            $this->_sn = $printer['sn'];
        }

        $this->httpClient = new HttpClient(self::API_URL, self::API_PORT);
    }

    /**
     * [打印订单接口 Open_printMsg]
     * @param  [string] $sn      [打印机编号sn]
     * @param  [string] $content [打印内容]
     * @param  [string] $times   [打印联数]
     * @return [string]          [接口返回值]
     */
    function printMsg($content, $order_id = null, $times = 1)
    {
        return $this->_base_fun([
            'sn' => $this->_sn,
            'content' => $content,
            'times' => $times,//打印次数
            'apiname' => "Open_printMsg"
        ], $order_id);
    }

    /**
     * 清空待打印的
     * @return bool
     */
    function clearMsg()
    {
        return $this->_base_fun([
            'apiname' => 'Open_delPrinterSqs',
            'sn' => $this->_sn,
        ]);
    }


    /**
     * [标签打印 Open_printLabelMsg]
     * @param  [string] $sn      [打印机编号sn]
     * @param  [string] $content [打印内容]
     * @param  [string] $times   [打印联数]
     * @return [string]          [接口返回值]
     */
    function printLabelMsg($content, $order_id = null, $times = 1)
    {
        return $this->_base_fun([
            'sn' => $this->_sn,
            'content' => $content,
            'times' => $times,//打印次数
            'apiname' => "Open_printLabelMsg"
        ], $order_id);
    }

    //提示：
    //$printerContent => 打印机编号sn(必填) # 打印机识别码key(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100台。
    //$printerContent = "sn1#key1#remark1#carnum1\nsn2#key2#remark2#carnum2";
    /**
     * [批量添加打印机接口 Open_printerAddlist]
     * @param  [string] $printerContent [打印机的sn#key, 打印机的sn#key, 打印机的sn#key]
     * @return [string]                 [接口返回值]
     */
    function addPrinterList($printerContent = [])
    {
        return $this->_base_fun([
            'printerContent' => implode("\n", $printerContent),
            'apiname' => "Open_printerAddlist"
        ]);
    }

    /**
     * [批量删除打印机 Open_printerDelList]
     * @param  [string] $snlist [打印机编号，多台打印机请用减号“-”连接起来]
     * @return [string]         [接口返回值]
     */
    function printerDelList($snlist)
    {
        return $this->_base_fun([
            'snlist' => $snlist,
            'apiname' => "Open_printerDelList"
        ]);
    }

    /**
     * [修改打印机信息接口 Open_printerEdit]
     * @param  [string] $sn       [打印机编号]
     * @param  [string] $name     [打印机备注名称]
     * @param  [string] $phonenum [打印机流量卡号码,可以不传参,但是不能为空字符串]
     * @return [string]           [接口返回值]
     */
    function printerEdit($sn = "", $name = "", $phonenum = "")
    {
        return $this->_base_fun([
            'sn' => $sn,
            'name' => $name,
            'phonenum' => $phonenum,
            'apiname' => "Open_printerEdit"
        ]);
    }

    /**
     * [删除订单接口 Open_delPrinterSqs]
     * @param  [string] $sn [打印机编号]
     * @return [string]     [接口返回值]
     */
    function delPrinterSqs($sn = null)
    {
        return $this->_base_fun(['sn' => $sn ?? $this->_sn, 'apiname' => "Open_delPrinterSqs"]);
    }

    /**
     * [获取某台打印机状态接口 Open_queryPrinterStatus]
     * @param  [string] $sn [打印机编号]
     * @return [string]     [接口返回值]
     */
    function queryPrinterStatus($sn)
    {
        return $this->_base_fun(['sn' => $sn ?? $this->_sn, 'apiname' => "Open_queryPrinterStatus"]);
    }

    public function set($sn = null)
    {
        $this->_sn = $sn;
    }

    private function _base_fun($param = [], $order_id = null)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => $this->_user,
            'stime' => $time,
            'sig' => $this->signature($time),
        );
        $msgInfo = array_merge($msgInfo, $param);

        if (!$this->httpClient->post(self::API_PATH, $msgInfo)) {
            return true;
        } else {
            $result = json_decode($this->httpClient->getContent(), true);
            $this->_add_log($msgInfo, $result['ret'], $result['msg'], $order_id);
//            return $result['data']['no'];
            return true;
        }
    }

    //增加日志
    private function _add_log($content = "", $ret = 0, $msg = "", $order_id = "")
    {
        /*PrinterLog::insert([
            'printer_sn' => $this->_sn,
            'content' => json_encode($content),
            'return_code' => $ret,
            'return_msg' => $msg,
            'order_id' => $order_id,
            'create_time' => time()
        ]);*/
        return true;
    }

    /**
     * [signature 生成签名]
     * @param  [string] $time [当前UNIX时间戳，10位，精确到秒]
     * @return [string]       [接口返回值]
     */
    function signature($time)
    {
        return sha1($this->_user . $this->_key . $time);//公共参数，请求公钥
    }


}